package com.flute.icrawler.app.task;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.app.task.entity.CrawlTask;

public class CrawlTaskPool {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(CrawlTaskPool.class);

	private List<CrawlTask> waitCrawlTaskList = new ArrayList<CrawlTask>();

	private List<CrawlTask> runningCrawlTaskList = new ArrayList<CrawlTask>();

	private List<CrawlTask> finishedCrawlTaskList = new ArrayList<CrawlTask>();

	/**
	 * 获取下一个可以执行的任务
	 * 
	 * @return
	 */
	public CrawlTask nextCrawlTask() {
		CrawlTask crawlTask = waitCrawlTaskList.remove(0);
		runningCrawlTaskList.add(crawlTask);
		return crawlTask;
	}

	/**
	 * 是否有下一个可以执行的任务
	 * 
	 * @return
	 */
	public synchronized boolean hasNext() {
		return waitCrawlTaskList.size() > 0;
	}

	/**
	 * 记录完成的任务
	 * 
	 * @param crawlTask
	 */
	public void recordFinished(CrawlTask crawlTask) {
		finishedCrawlTaskList.add(crawlTask);
	}

	/**
	 * 是否包含该任务
	 * 
	 * @param taskName
	 *            任务名称
	 * @return
	 */
	public boolean contain(String taskName) {
		synchronized (waitCrawlTaskList) {
			int size = waitCrawlTaskList.size();
			for (int i = 0; i < size; i++) {

				// 任务名称相同
				if (taskName.equalsIgnoreCase(waitCrawlTaskList.get(i)
						.getName())) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 添加一个任务到池中
	 * 
	 * @param crawlResult
	 */
	public void addCrawlTask(CrawlTask crawlTask) {
		synchronized (waitCrawlTaskList) {

			waitCrawlTaskList.add(crawlTask);

			LOGGER.debug("CrawlTaskPool:{}",
					"add 1 task name=" + crawlTask.getName());

		}
	}

	public boolean removeCrawlTask(CrawlTask crawlTask) {
		synchronized (waitCrawlTaskList) {

			LOGGER.debug("CrawlTaskPool:{}",
					"remove 1 task name=" + crawlTask.getName());

			return waitCrawlTaskList.remove(crawlTask);

		}
	}

	/**
	 * 从池中取出所有数据 拷贝到一个List中
	 * 
	 * @return
	 */
	public List<CrawlTask> copyAllCrawlTasks() {

		List<CrawlTask> resultList = new ArrayList<CrawlTask>();
		synchronized (waitCrawlTaskList) {

			// 将数据全部取出来
			if (waitCrawlTaskList.size() > 0) {

				resultList.addAll(waitCrawlTaskList);

				return resultList;
			}

			return resultList;

		}
	}

	public int size() {
		synchronized (waitCrawlTaskList) {
			return waitCrawlTaskList.size();
		}
	}

	/**
	 * 取出一个任务
	 * 
	 * @return
	 */
	public CrawlTask get(int i) {

		CrawlTask crawlTask = null;
		synchronized (waitCrawlTaskList) {

			// 将第一个数据取出来
			crawlTask = waitCrawlTaskList.get(i);
		}

		return crawlTask;

	}

}
